// 引用API文件
import api from '@/api/index.js';

const state = {
  token: '',
  navList: []
};

const mutations = {
  setNavList: (state, data) => {
    state.navList = data;
  }
};

const actions = {
  // 获取该用户的菜单列表
  getNavList ({commit}) {
    return new Promise((resolve) => {
      api.post('/user/navlist', {}, r => {
        commit('setNavList', r);
        resolve(r);
      }, r => {
        console.log(r.msg);
      });
    });
  },

  // 将菜单列表扁平化形成权限列表
  getPermissionList ({state}) {
    return new Promise((resolve) => {
      let permissionList = [];
      // 将菜单数据扁平化为一级
      function flatNavList (arr) {
        for (let v of arr) {
          if (v.child && v.child.length) {
            flatNavList(v.child);
          } else {
            permissionList.push(v);
          }
        }
      }
      flatNavList(state.navList);
      resolve(permissionList);
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
